import { Leafer, Pen, DragEvent, App } from 'leafer-ui'
import { ITool, IToolConfig } from '../types'
export const PenTool: ITool = ({ app, config, target, commit }) => {
	let pen: Pen
	let isDrawing = false
	const initPen = () => {
		pen = new Pen()
		target().add(pen)
	}
	const startDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		initPen()
		isDrawing = true
		const point = e.getPagePoint()
		pen.setStyle({
			stroke: config.pen.color,
			strokeWidth: config.pen.strokeWidth / (app.data?.fitScale ?? 1),
			strokeCap: 'round',
			strokeJoin: 'round',
			opacity: config.pen.opcity
		})
		pen.moveTo(point.x, point.y)
	}
	const continueDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		if (!isDrawing) return
		const point = e.getPagePoint()
		pen.lineTo(point.x, point.y)
	}
	const stopDrawing = () => {
		isDrawing = false
		// pen = null;
		commit()
	}
	const eventsMap = {
		[DragEvent.START]: startDrawing,
		[DragEvent.DRAG]: continueDrawing,
		[DragEvent.END]: stopDrawing
	}
	return {
		eventsMap,
		active: () => {},
		deactive: () => {}
	}
}
